<!--
 * @Author: wjj3
 * @Date: 2023-1-19 10:30:17
 * @Description: 所有工作
-->
<template>
  <div class="list-container">
    <div class="search-container">
      <el-form v-model="searchParams" ref="elForm" label-width="100px" size="medium">
        <el-row>
          <el-col :span="6">
            <el-form-item label="文种：" class="scripts">
              <el-select
                v-model="searchParams.processDefKeys"
                clearable
                placeholder="请选择需要查询的文种"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.processDefinitionName"
                  :value="item.processDefinitionKey">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="标题：" class="scripts">
              <el-input
                v-model="searchParams.applyTitle"
                placeholder="请输入标题"
                class="w100"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="办理状态：">
              <el-select v-model="searchParams.processState" clearable placeholder="请选择办理状态">
                <el-option
                  v-for="item in stateData"
                  :key="item.stateCode"
                  :label="item.stateName"
                  :value="item.stateCode">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" class="operate-btn">
            <el-button size="small" class="searchBtn" type="primary" @click="search">查询</el-button>
            <el-button size="small" class="searchBtn" type="primary" @click="resetFields">取消</el-button>
          </el-col>
        </el-row>
        <el-row>
          <!-- <el-col :span="6">
            <el-form-item label="新建流程标记：">
              <el-select v-model="searchParams.newProcessFlag" clearable placeholder="请选择">
                <el-option
                  v-for="item in processSignList"
                  :key="item.value"
                  :label="item.signName"
                  :value="item.signValue">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item prop="range" label="处理日期：">
              <el-date-picker
                v-model="searchParams.range"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="timestamp"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="table-container">
      <jdf-table
        v-loading="loading"
        :columns="columns"
        :data="tableData"
        :table-attrs="tableAttrs"
        :pagination-attrs="paginationAttrs"
        :pagination-events="paginationEvents"
        :table-events="tableEvents"
      ></jdf-table>
    </div>
    <jdf-render-dialog
      v-if="renderVisible"
      :visible.sync="renderVisible"
      :flow-visible.sync="renderVisible"
      :item="getItem()"
    >
    </jdf-render-dialog>
  </div>
</template>

<script>
import dayjs from 'dayjs';
import { alertErrorMsg, renderLink, timeConvert } from 'jdf-util';
import { ProcessService } from 'jdf-jssdk';
import BizMaintainService from '@/api/domains/BizMaintainService';
import routerJump from '@/api/utils/router-jump';
import { bizServiceURL } from '@/api/utils/constants';
import listTableMixins from '@/mixins/listTableMixins';
import settings from '@/settings/settings';
import { isEmpty, uniq, omit } from 'lodash-es';

export default {
  mixins: [listTableMixins],
  data() {
    return {
      renderVisible: false,
      renderComponentName: null,
      renderAttrs: {},
      renderEvents: {},
      service: BizMaintainService,
      functionName: 'getArrWork',
      // 获取起草名称
      options: [],
      // 办理状态数据
      stateData: [
        {
          stateCode: 'RUNNING',
          stateName: '进行中'
        }, {
          stateCode: 'ENDING',
          stateName: '已结束'
        }
      ],
      // 流程实例状态
      processStateList: [
        {
          stateValue: '1',
          stateName: '运行'
        },
        {
          stateValue: '2',
          stateName: '结束'
        },
      ],
      // 流程标记
      processSignList: [
        {
          signValue: 1,
          signName: '排除新建流程'
        },
        {
          signValue: 2,
          signName: '只查询新建流程'
        },
      ],
      columns: [
        {
          type: 'index',
          width: 50,
          label: '序号',
          attrs: {
            align: 'center',
            index: i => this.getTableRowIndexNo(i)
          }
        },
        {
          prop: 'applyTitle',
          label: '标题',
          width: 250,
          attrs: {
            'show-overflow-tooltip': true
          },
          render: (h, params) => renderLink(h, params.row.applyTitle, () => this.openTaskForm(params.row), 'pj-title'),
          // render: (h, params) => renderLink(h, params.row.applyTitle, () => {})
        },
        {
          prop: 'templateName',
          width: 100,
          label: '文种',
          attrs: {
            align: 'center',
            'show-overflow-tooltip': true,
          }
        },
        {
          prop: 'businessHotExtend2',
          width: 150,
          label: '文件编号',
          attrs: {
            align: 'center',
            'show-overflow-tooltip': true,
          }
        },
        {
          prop: 'applicantOrgName',
          width: 100,
          label: '起草部门',
          attrs: {
            align: 'center',
            'show-overflow-tooltip': true,
          }
        },
        {
          prop: 'applicantUserName',
          width: 80,
          label: '起草人',
          attrs: {
            align: 'center',
            'show-overflow-tooltip': true,
          }
        },
        {
          prop: 'currentOrgName',
          width: 220,
          label: '办理部门',
          attrs: {
            align: 'center',
            'show-overflow-tooltip': true,
          }
        },
        {
          prop: 'currentNodeUser',
          width: 120,
          label: '当前环节处理人',
          attrs: {
            align: 'center',
            'show-overflow-tooltip': true
          }
        }, {
          prop: 'currentNodeName',
          width: 180,
          label: '当前处理环节',
          attrs: {
            align: 'center',
            'show-overflow-tooltip': true
          }
        }, {
          prop: 'state',
          width: 90,
          label: '办理状态',
          attrs: {
            align: 'center',
            formatter: (row) => (row.state === 'RUNNING' ? '进行中' : '已结束')
          }
        },
        {
          prop: 'createTime',
          label: '创建时间',
          width: 200,
          attrs: {
            align: 'center',
            formatter: (row) => timeConvert(row.createTime, 'YYYY-MM-DD HH:mm:ss')
          }
        },
        {
          label: '流程跟踪',
          width: 80,
          attrs: {
            align: 'center',
          },
          render: (h, params) => renderLink(h, '流程跟踪', () => this.openFlowDialog(params.row)),
        }
      ],
      // 表格事件集合
      tableEvents: {
        'row-click': () => {},
      }
    };
  },
  mounted() {
    this.jurisdiction();
    this.getList();
  },
  computed: {
    /**
     * 获取数据请求参数，把查询参数和分页数据合并为请求后台参数
     */
    param() {
      const {
        range = []
      } = this.searchParams;
      // 时间选择是范围，第一个是开始日期，第二个是结束日期，结束日期为某天零点，查询时不包含这一天，所以默认加一天减1秒为这一天最后一刻
      const otherParam = isEmpty(range) ? {} : {
        startTime: range[0],
        endTime: dayjs(range[1]).add(1, 'day').valueOf() - 1
      };
      return {
        ...omit(this.searchParams, ['range']),
        page: this.pageNumber,
        pageSize: this.pageSize,
        ...otherParam
      };
    },
  },
  methods: {
    /**
     * 根据组件类型获取组件配置
     */
    getItem() {
      const item = {
        type: this.renderComponentName,
        attrs: this.renderAttrs,
        on: this.renderEvents,
      };
      return item;
    },
    async jurisdiction() {
      const { data: { data } } = await BizMaintainService.flowPath();
      this.options = data;
    },
    /**
     * 点击行打开流程表单
     */
    async openTaskForm(row) {
      const [{ task }] = await new ProcessService(bizServiceURL).getProcessFlowList(row.piid);
      routerJump.jumpToNewWindow('/process-form-oa', {
        taskId: task.taskId,
        processDefinitionKey: row.processDefinitionKey ?? row.templateId,
        piid: row.processInstanceId ?? row.piid,
        maintainField: 'maintainTrue'
      });
    },
    /**
     * 打开流程跟踪
     * @param {*} row
     */
    openFlowDialog(row) {
      this.renderComponentName = 'jdf-process-flow';
      this.renderAttrs = {
        piid: row.piid,
        ref: 'processFlowRef',
        columns: settings.templateAttrs.processFlowColumns,
        dialogTitle: settings.templateAttrs.processFlowDialogTitle,
        dialogWidth: settings.templateAttrs.processFlowDialogWidth,
        tableAttrs: settings.templateAttrs.processTableAttrs,
        'show-view-chart-btn': true
      };
      this.renderVisible = true;
    },
    /**
     * 根据查询参数获取表格数据
     * @param {Number} pageNum 当前查询的页码，默认1
     * @param {Boolean} isDelete 是否是删除后回刷列表
     */
    async getList(cur = 1) {
      this.pageNumber = cur;
      try {
        this.loading = true;
        const data = await this.service[this.functionName]({
          ...this.param,
          ...(this.otherParams ?? {}),
        });
        this.total = data.total;
        const tableData = data.pageList ?? data.records;
        this.tableData = await Promise.all(tableData.map(async (t) => {
          const res = await BizMaintainService.getCurrentNode(t.piid);
          return {
            ...t,
            currentNodeName: uniq(res.map(v => v.nodeName)).join('，'),
            currentNodeUser: uniq(res.map(v => v.handler?.userName).filter(Boolean)).join('，'),
            currentOrgName: uniq(res.map(v => v.handler?.orgName).filter(Boolean)).join('，'),
          };
        }));
      } catch (error) {
        alertErrorMsg(error);
      } finally {
        this.loading = false;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .pj-select {
  .el-select__tags {
    .el-tag {
      max-width: 85px;
    }
  }
}
</style>
